package com.ruoyi.develop.projectBaseInfo.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsInvoice.domain.GoodsInvoice;
import com.ruoyi.develop.goodsOrderIn.domain.GoodsOrderIn;
import com.ruoyi.develop.goodsOrderIn.service.IGoodsOrderInService;
import com.ruoyi.develop.goodsReimbursement.domain.GoodsReimbursement;
import com.ruoyi.develop.goodsReimbursementDetail.domain.GoodsReimbursementDetail;
import com.ruoyi.develop.goodsSale.domain.GoodsSale;
import com.ruoyi.develop.goodsSale.service.IGoodsSaleService;
import com.ruoyi.develop.goodsSaledo.domain.GoodsSaledo;
import com.ruoyi.develop.goodsSaledo.service.IGoodsSaledoService;
import com.ruoyi.develop.goodsScalaAll.service.IGoodsScalaAllService;
import com.ruoyi.develop.lvDo.domain.LvDo;
import com.ruoyi.develop.lvDo.service.ILvDoService;
import com.ruoyi.export.service.impl.ExportServiceImpl;
import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.util.SystemOutLogger;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.projectBaseInfo.domain.ProjectBaseInfo;
import com.ruoyi.develop.projectBaseInfo.service.IProjectBaseInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 订单基础信息管理Controller
 *
 * @author qh
 * @date 2023-01-10
 */
@RestController
@RequestMapping("/projectBaseInfo/projectBaseInfo")
public class ProjectBaseInfoController extends BaseController {
    @Autowired
    private IProjectBaseInfoService projectBaseInfoService;
    @Autowired
    private IGoodsSaleService goodsSaleService;
    @Autowired
    private IGoodsScalaAllService iGoodsScalaAllService;
    @Autowired
    private IGoodsOrderInService goodsOrderInService;
    @Autowired
    private ExportServiceImpl exportService;
    @Autowired
    private IGoodsSaledoService goodsSaledoService;
    @Resource
    private ILvDoService lvDoService;

    /**
     * 查询订单基础信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('develop:ProjectBaseInfo:query')")
    @GetMapping("/list")
    public TableDataInfo list(ProjectBaseInfo entity) {
        startPage();
        List<ProjectBaseInfo> list = projectBaseInfoService.selectList(entity);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('develop:ProjectBaseInfo:query')")
    @GetMapping("/listNotTiejian")
    public TableDataInfo listNotTiejian(ProjectBaseInfo entity) {
        startPage();
        List<ProjectBaseInfo> list = projectBaseInfoService.listNotTiejian(entity);
        return getDataTable(list);
    }

    /**
     * 查询未完成开票的订单
     */
    @PreAuthorize("@ss.hasPermi('develop:ProjectBaseInfo:query')")
    @GetMapping("/listNotAllKp")
    public TableDataInfo listNotAllKp(ProjectBaseInfo entity) {
        startPage();
        List<ProjectBaseInfo> list = projectBaseInfoService.listNotAllKp(entity);
        return getDataTable(list);
    }

    @GetMapping("/listByArea")
    public TableDataInfo listByArea(ProjectBaseInfo entity) {
        //startPage();
        List<ProjectBaseInfo> list = projectBaseInfoService.listByAreaGroup(entity);
        for (ProjectBaseInfo projectBaseInfo : list) {
            projectBaseInfo.setArea(DictUtils.getDictLabel("order_area", projectBaseInfo.getArea()));
        }
        return getDataTable(list);
    }

    @GetMapping("/listByStatusGroup")
    public TableDataInfo listByStatusGroup(ProjectBaseInfo entity) {
        //startPage();
        List<ProjectBaseInfo> list = projectBaseInfoService.listByStatusGroup(entity);
        for (ProjectBaseInfo projectBaseInfo : list) {
            projectBaseInfo.setStatus(DictUtils.getDictLabel("goods_status", projectBaseInfo.getStatus()));
        }
        return getDataTable(list);
    }

    @GetMapping("/listBySourceGroup")
    public TableDataInfo listBySourceGroup(ProjectBaseInfo entity) {
        //startPage();
        List<ProjectBaseInfo> list = projectBaseInfoService.listBySourceGroup(entity);
        for (ProjectBaseInfo projectBaseInfo : list) {
            projectBaseInfo.setSource(DictUtils.getDictLabel("project_source", projectBaseInfo.getSource()));
        }
        return getDataTable(list);
    }

    @GetMapping("/listByYearGroup")
    public TableDataInfo listByYearGroup(ProjectBaseInfo entity) {
        //startPage();
        List<ProjectBaseInfo> list = projectBaseInfoService.listByYearGroup(entity);
        return getDataTable(list);
    }

    @GetMapping(value = "/listCount")
    public AjaxResult listCount() {
        return AjaxResult.success(projectBaseInfoService.listCount());
    }

    @GetMapping(value = "/listMoney")
    public AjaxResult listMoney() {
        return AjaxResult.success(projectBaseInfoService.listMoney());
    }

    /**
     * 导出订单基础信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('develop:ProjectBaseInfo:export')")
    @Log(title = "订单基础信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProjectBaseInfo entity) {
        List<ProjectBaseInfo> list = projectBaseInfoService.selectList(entity);
        ExcelUtil<ProjectBaseInfo> util = new ExcelUtil<ProjectBaseInfo>(ProjectBaseInfo.class);
        util.exportExcel(response, list, "订单基础信息管理数据");
    }

    @Log(title = "订单统计信息导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportPro")
    public void exportPro(HttpServletRequest request, HttpServletResponse response, ProjectBaseInfo entity) {
        projectBaseInfoService.exportPro(request, response, entity);
    }

    @PutMapping
    public AjaxResult updateSaleBatch(@Validated @RequestBody ProjectBaseInfo entity) {
        projectBaseInfoService.update(entity);
        for (GoodsSale goodsSale : entity.getColumns()) {
            if (goodsSale != null) {
                if (!goodsSale.getStatus().equals(BusinessConstants.STATUS_YES)) {
                    GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(goodsSale.getGoodsId());
                    if (goodsOrderIn != null) {
                        goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().multiply(goodsSale.getGoodsCount()));
                        goodsOrderInService.update(goodsOrderIn);
                    }
                }
            }
            goodsSale.setStatus(BusinessConstants.STATUS_YES);
            goodsSaleService.update(goodsSale);
        }
        return AjaxResult.success("成功");
    }

    /**
     * 获取订单基础信息管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:ProjectBaseInfo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(projectBaseInfoService.selectById(id));
    }

    /**
     * 新增订单基础信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:ProjectBaseInfo:add')")
    @Log(title = "订单基础信息管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ProjectBaseInfo entity) {
        if (UserConstants.NOT_UNIQUE.equals(projectBaseInfoService.checkCodeUnique(entity.getCode()))) {
            return AjaxResult.error("新增订单'" + entity.getCode() + "'失败，订单编号已存在");
        }
        return toAjax(projectBaseInfoService.insert(entity));
    }

    /**
     * 修改订单基础信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:ProjectBaseInfo:edit')")
    @Log(title = "订单基础信息管理", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody ProjectBaseInfo entity) {
        return toAjax(projectBaseInfoService.update(entity));
    }

    /**
     * 删除订单基础信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:ProjectBaseInfo:remove')")
    @Log(title = "订单基础信息管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(projectBaseInfoService.deleteByIds(ids));
    }


    @GetMapping(value = "/prjNames")
    public AjaxResult prjNames(ProjectBaseInfo param) {
        List<SysDictData> nameList = projectBaseInfoService.selectAllProject(param);
        Map<String, Object> retMap = new HashedMap();
        retMap.put("nameList", nameList);
        return AjaxResult.success(retMap);
    }

    @GetMapping("/exportBaseInfo")
    public AjaxResult exportBaseInfo(ProjectBaseInfo entity, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        String date = DateUtils.getTime();//默认当天
        List<ProjectBaseInfo> list = projectBaseInfoService.selectList(entity);
        list.stream().forEach(e -> {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("contractDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getContractDate()));
            map.put("invoice", DictUtils.getDictLabel(BusinessConstants.YES_NO, e.getTaxStatus()));
            map.put("fundCallback", DictUtils.getDictLabel(BusinessConstants.FUND_CALLBACK, e.getFundCallback()));
            e.setParams(map);
        });
        params.put("list", list);
        params.put("date", date);
        String fileName = request.getParameter("fileName");
        if (StringUtils.isBlank(fileName)) {
            fileName = "订单信息.xlsx";
        }
        String templateName = "订单记录.xlsx";
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
        return null;
    }

    @GetMapping(value = "refreshProfit")
    public AjaxResult refreshProfit(ProjectBaseInfo projectBaseInfo) {
        return projectBaseInfoService.refreshProfit(projectBaseInfo);
    }

    @GetMapping("/exportExcel")
    public void exportExcel(String id, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        params = projectBaseInfoService.getExportData(id);
        String fileName = request.getParameter("fileName");
        if (StringUtils.isBlank(fileName)) {
            fileName = "订单详细信息.xlsx";
        }
        String templateName = "订单详细信息.xlsx";
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
    }

    @Log(title = "订单信息导入数据", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(ProjectBaseInfo entity, MultipartFile file) {
        Map<String, Object> error = new HashMap<>();
        error = projectBaseInfoService.importData(entity, file);
        error.put("code", 200);
        return AjaxResult.success(error);
    }


    @Log(title = "h合同产品导入数据", businessType = BusinessType.INSERT)
    @PostMapping("/imporGoodsChuan")
    public AjaxResult imporGoodsChuan(ProjectBaseInfo entity, MultipartFile file) {
        Map<String, Object> error = new HashMap<>();
        error = projectBaseInfoService.imporGoodsChuan(entity, file);
        error.put("code", 200);
        return AjaxResult.success(error);
    }


    @Log(title = "订单产品信息导入数据", businessType = BusinessType.INSERT)
    @PostMapping("/importOrderAndGoodsData")
    public AjaxResult importOrderAndGoodsData(ProjectBaseInfo entity, MultipartFile file) {
        Map<String, Object> error = new HashMap<>();
        error = projectBaseInfoService.importOrderAndGoodsData(entity, file);
        error.put("code", 200);
        return AjaxResult.success(error);
    }

    @Log(title = "铁构件订单信息导入数据", businessType = BusinessType.INSERT)
    @PostMapping("/importOrderForIron")
    public AjaxResult importOrderForIron(ProjectBaseInfo entity, MultipartFile file) {
        Map<String, Object> error = new HashMap<>();
        error = projectBaseInfoService.importIronOrderData(entity, file);
        error.put("code", 200);
        return AjaxResult.success(error);
    }

    @Log(title = "铁构件订单信息导入数据", businessType = BusinessType.INSERT)
    @PostMapping("/importOrderNoGoods")
    public AjaxResult importOrderNoGoods(ProjectBaseInfo entity, MultipartFile file) {
        Map<String, Object> error = new HashMap<>();
        error = projectBaseInfoService.importOrderNoGoods(entity, file);
        error.put("code", 200);
        return AjaxResult.success(error);
    }


    @Log(title = "铁构件订单信息导入数据（带明细）", businessType = BusinessType.INSERT)
    @PostMapping("/importOrderForIronDetail")
    public AjaxResult importOrderForIronDetail(ProjectBaseInfo entity, MultipartFile file) {
        Map<String, Object> error = new HashMap<>();
        error = projectBaseInfoService.importOrderForIronDetail(entity, file);
        error.put("code", 200);
        return AjaxResult.success(error);
    }

    @Log(title = "修改项目状态", businessType = BusinessType.UPDATE)
    @GetMapping("/submitProject")
    public AjaxResult submitProject(ProjectBaseInfo entity, HttpServletRequest request) {
        String goodsSaleIds = request.getParameter("goodsSaleIds");
        String status = entity.getStatus();
        for (String goodsSaleId : goodsSaleIds.split(",")) {
            GoodsSale goodsSale = new GoodsSale();
            goodsSale.setId(goodsSaleId);
            goodsSale.setStatus(status);
            goodsSaleService.update(goodsSale);
        }

//        goodsSaleService.updateStatusByPro(id,status);
//        iGoodsScalaAllService.updateStatusByPro(id,status);
//        ProjectBaseInfo projectBaseInfo=projectBaseInfoService.selectById(entity);
//        projectBaseInfo.setStatus(status);
        return toAjax(projectBaseInfoService.update(entity));
    }

    @Log(title = "发起提交采购", businessType = BusinessType.UPDATE)
    @GetMapping("/submitProjectScalaDo")
    public AjaxResult submitProjectScalaDo(String id, String status) {
        ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(id);
        GoodsSaledo goodsSaledo = new GoodsSaledo();
        goodsSaledo.setProjectId(id);
        List<GoodsSaledo> goodsSaledoList = goodsSaledoService.listByProjectId(goodsSaledo);
        if (goodsSaledoList.size() > 0) {
            LvDo lvdo = new LvDo();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String time = sdf.format(new Date());
            lvdo.setMainId(projectBaseInfo.getId());
            lvdo.setName(projectBaseInfo.getName());
            lvdo.setCode(projectBaseInfo.getCode());
            lvdo.setNos(time);
            lvdo.setStatus(status);//22:请购中,4:采购中
            lvdo.setDdDate(projectBaseInfo.getContractDate());
            lvdo.setMoney(projectBaseInfo.getContractMoney());
            //lvdo.setSubDate();//需求日期
            lvdo.setCustomerId(projectBaseInfo.getCustomId());
            lvdo.setCustomerName(projectBaseInfo.getCustomName());
            lvdo.setDeptId(projectBaseInfo.getDeptId());
            lvdo.setDeptName(projectBaseInfo.getDeptName());
            lvDoService.insert(lvdo);
            for (GoodsSaledo goodsSaledo1 : goodsSaledoList) {
                goodsSaledo1.setStatus(status);//22:请购中,4:采购中
                goodsSaledo1.setMainId(lvdo.getId());
                goodsSaledo1.setNos(lvdo.getNos());
                goodsSaledoService.update(goodsSaledo1);
            }
        }
        projectBaseInfo.setStatus(status);
        return toAjax(projectBaseInfoService.update(projectBaseInfo));
    }

    /**
     * 检查订单编号是否存在
     */
    @GetMapping(value = "/checkCodeUnique/{code}")
    public AjaxResult checkCodeUnique(@PathVariable("code") String code) {
        if (UserConstants.UNIQUE.equals(projectBaseInfoService.checkCodeUnique(code))) {
            return AjaxResult.success(true);
        } else {
            return AjaxResult.success(false);
        }
    }


    /**
     * 提交订单
     */
    @Log(title = "订单基础信息管理", businessType = BusinessType.UPDATE)
    @GetMapping("/submit/{ids}")
    public AjaxResult submit(@PathVariable String[] ids) {
        List<ProjectBaseInfo> projectBaseInfoList = new ArrayList<>();
        for (String id : ids) {
            ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(id);
            projectBaseInfoList.add(projectBaseInfo);

        }
        for (ProjectBaseInfo projectBaseInfo : projectBaseInfoList) {
            if (!BusinessConstants.PROJECT_0.equals(projectBaseInfo.getStatus())) {
                return AjaxResult.error("订单状态不是待提交状态，不能提交");
            }
        }

        for (ProjectBaseInfo projectBaseInfo : projectBaseInfoList) {
            GoodsSale goodsSale = new GoodsSale();
            goodsSale.setProjectId(projectBaseInfo.getId());
            List<GoodsSale> goodsSaleList = goodsSaleService.selectList(goodsSale);
            for (GoodsSale sale : goodsSaleList) {
                sale.setStatus(BusinessConstants.GOODS_1);
                goodsSaleService.update(sale);
            }
            projectBaseInfo.setStatus(BusinessConstants.PROJECT_1);
            projectBaseInfoService.update(projectBaseInfo);
        }

        return AjaxResult.success();
    }

    /**
     * 库管订单弃审
     */
    @GetMapping("/storeReject/{ids}")
    public AjaxResult storeReject(@PathVariable String[] ids) {
        for (String id : ids) {
            ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(id);
            if (!BusinessConstants.PROJECT_1.equals(projectBaseInfo.getStatus())) {
                return AjaxResult.error("订单" + projectBaseInfo.getCode() + "状态不是库管审核状态，不能弃审");
            } else {
                projectBaseInfo.setStatus(BusinessConstants.PROJECT_0);
                GoodsSale goodsSale = new GoodsSale();
                goodsSale.setProjectId(projectBaseInfo.getId());
                List<GoodsSale> goodsSaleList = goodsSaleService.selectList(goodsSale);
                for (GoodsSale sale : goodsSaleList) {
                    sale.setStatus(BusinessConstants.GOODS_0);
                    goodsSaleService.update(sale);
                }
                projectBaseInfoService.update(projectBaseInfo);
            }
        }
        return AjaxResult.success("弃审成功");
    }


    /**
     * 关闭订单
     */
    @Log(title = "关闭订单", businessType = BusinessType.UPDATE)
    @Transactional
    @GetMapping("/close/{id}")
    public AjaxResult close(@PathVariable String id) {
        ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(id);
        if (BusinessConstants.STATUS_YES.equals(projectBaseInfo.getStatus())) {
            return AjaxResult.error("订单已经关闭，不能再次关闭");
        }
        projectBaseInfo.setIsClosed(BusinessConstants.STATUS_YES);
        projectBaseInfoService.update(projectBaseInfo);
        GoodsSale goodsSale = new GoodsSale();
        goodsSale.setProjectId(projectBaseInfo.getId());
        List<GoodsSale> goodsSaleList = goodsSaleService.selectList(goodsSale);
        for (GoodsSale goods : goodsSaleList) {
            if (BusinessConstants.STATUS_NO.equals(goods.getIsclose())) {
                goods.setIsclose(BusinessConstants.STATUS_YES);
                // 还回去 已经锁定的库存
                if (goods.getLockCount().compareTo(BigDecimal.ZERO)>0){
                    GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(goods.getGoodsId());
                    goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().add(goods.getLockCount()));
                    goodsOrderInService.update(goodsOrderIn);
                    goods.setLockCount(BigDecimal.ZERO);
                    goodsSaleService.update(goods);
                }
            }
        }
        return AjaxResult.success();
    }


}
